//
//  PlayVideoViewController.m
//  WWXELuShang
//
//  Created by lanou on 15/12/21.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "PlayVideoViewController.h"
#import "VideoPlayView.h"
#import "PlayerView.h"
#import <AVFoundation/AVFoundation.h>

@interface PlayVideoViewController ()

@property (nonatomic, strong)AVPlayer *player;

@property (nonatomic, strong)AVPlayerItem *playerItem;

@property (nonatomic, strong)VideoPlayView *videoPlayView;

@property (nonatomic, strong)id playbackTimeObserver;

@property (nonatomic, strong)NSDateFormatter *dateFormatter;

@property (nonatomic, strong)NSString *totalTime;

@property (nonatomic, assign)BOOL played;

@property (nonatomic, strong)UIActivityIndicatorView *activityView;

@property (nonatomic, assign)BOOL statusBarHidden;

@end

@implementation PlayVideoViewController

- (UIActivityIndicatorView *)activityView {
    
    if (!_activityView) {
        _activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
        _activityView.center = CGPointMake(kWidth / 2, kHeight / 2);
        [self.view addSubview:_activityView];
    }
    
    return _activityView;
    
}

- (VideoPlayView *)videoPlayView {
    if (!_videoPlayView) {
        _videoPlayView = [[VideoPlayView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    
    
    return _videoPlayView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.statusBarHidden = NO;
    self.videoPlayView.timeLabel.text = self.time;
    self.view = self.videoPlayView;
    self.view.backgroundColor = [UIColor blackColor];
    [self.activityView startAnimating];
    [self.videoPlayView.backButton addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.videoPlayView.stateButton addTarget:self action:@selector(stateButtonTouched:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.videoPlayView.videoSlider addTarget:self action:@selector(videoSlierChangeValue:) forControlEvents:(UIControlEventValueChanged)];
    [self.videoPlayView.fullButton addTarget:self action:@selector(changeDirection) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(controlHidden)];
    [self.videoPlayView.playerView addGestureRecognizer:tap];
    
    
    NSURL *videoUrl = [NSURL URLWithString:self.urlString];
    self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    [self.playerItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil];//监听status
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:(NSKeyValueObservingOptionNew) context:nil];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.videoPlayView.playerView.player = _player;
    self.videoPlayView.stateButton.userInteractionEnabled = NO;
    self.videoPlayView.videoSlider.userInteractionEnabled = NO;
    
    //添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
    
    // Do any additional setup after loading the view.
}

//KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"准备播放");
            [self.activityView stopAnimating];
            if (self.played) {
                [self.videoPlayView.playerView.player play];
            }
            self.videoPlayView.stateButton.userInteractionEnabled = YES;
            self.videoPlayView.videoSlider.userInteractionEnabled = YES;
            CMTime duration = self.playerItem.duration;//获取视频总长度
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;//转换成秒
            _totalTime = [self convertTime:totalSecond];//转换成播放时间
            [self customVideoSlider:duration];//自定义slider外观
            [self monitoringPlayback:self.playerItem];//监听播放状态
        }else if ([playerItem status] == AVPlayerStatusFailed){
            NSLog(@"缓冲失败");
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];//计算缓冲进度
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.videoPlayView.videoProgress setProgress:timeInterval / totalDuration animated:YES];
    }
    
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}


- (void)stateButtonTouched:(UIButton *)button {
    if (!_played) {
        [self.videoPlayView.playerView.player play];
        [self.videoPlayView.stateButton setImage:[[UIImage imageNamed:@"download_pause_selected@2x"]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
        [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(controlHidden) userInfo:nil repeats:NO];
        
    }else {
        [self.videoPlayView.playerView.player pause];
        [self.videoPlayView.stateButton setImage:[[UIImage imageNamed:@"download_begain@2x"]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    }
    _played = !_played;
}

- (void)controlHidden {
    [self.videoPlayView controlMakeHidden];
}

- (void)changeDirection {
    
    self.statusBarHidden = !self.statusBarHidden;
    [self setNeedsStatusBarAppearanceUpdate];//刷新状态栏
    [self.videoPlayView changeDirection];
}

- (BOOL)prefersStatusBarHidden {
    //是否显示状态栏
    return self.statusBarHidden;
}


//显示时间
- (NSString *)convertTime:(CGFloat)second {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:second];
    if (second / 3600 >= 1) {
        [self.dateFormatter setDateFormat:@"HH:mm:ss"];
    }else {
        [self.dateFormatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [self.dateFormatter stringFromDate:date];
    return showtimeNew;
}

//自定义slider
- (void)customVideoSlider:(CMTime)duration {
    self.videoPlayView.videoSlider.maximumValue = CMTimeGetSeconds(duration);
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    [self.videoPlayView.videoSlider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
    [self.videoPlayView.videoSlider setMaximumTrackImage:transparentImage forState:(UIControlStateNormal)];
    
}

- (void)videoSlierChangeValue:(UISlider *)slider {
    
    
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    
    __weak typeof(self) weakSelf = self;
    [self.videoPlayView.playerView.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        
        if (self.played) {
            [weakSelf.videoPlayView.playerView.player play];
            [self.videoPlayView.stateButton setImage:[[UIImage imageNamed:@"download_pause_selected@2x"]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
        }
        
    }];
    
}
//计算缓冲区域
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.videoPlayView.playerView.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];//获取缓冲区域
    CGFloat startSeconds = CMTimeGetSeconds(timeRange.start);
    CGFloat durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;//计算缓冲进度
    return result;
    
}


//监听播放状态
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    __weak typeof(self) weakSelf = self;
    self.playbackTimeObserver = [self.videoPlayView.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        CGFloat currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;//计算当前在第几秒
        [weakSelf.videoPlayView.videoSlider setValue:currentSecond animated:YES];
        NSString *timeString = [weakSelf convertTime:currentSecond];
        weakSelf.videoPlayView.nowTimeLabel.text = [NSString stringWithFormat:@"%@",timeString];
        
    }];//
    
    
}

- (void)moviePlayDidEnd:(NSNotification *)notification {
    NSLog(@"Play end");
    __weak typeof(self) weakSelf = self;
    [self.videoPlayView.playerView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        [weakSelf.videoPlayView.videoSlider setValue:0.0 animated:YES];
        [self.videoPlayView.stateButton setImage:[[UIImage imageNamed:@"download_begain@2x"]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    }];
    
    
}

- (void)dealloc {
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    [self.videoPlayView.playerView.player removeTimeObserver:self.playbackTimeObserver];
}


- (void)back {
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
